import { defineStore } from "pinia";
import { deleteCartList, getCartList, putCartList } from '../api/index.js';

export const useCart = defineStore("cartStore", {
  state: () => {
    return {
      cartList: []
    }
  },
  actions: {
    changeCartList(list) {
      this.cartList = list.map(item => {
        item.checked = true;
        return item
      })
    },
    getCartListAsync() {
      getCartList().then(data => {
        this.changeCartList(data.data || [])
      })
    },
    delCartListAsync(id) {
      deleteCartList(id).then(res => {
        if (res.resultCode === 200) {
          //刷新购物车
          this.getCartListAsync()
        }
      })
    },
    async putCartListAsync(cartItemId, goodsCount) {
      let res = await putCartList(cartItemId, goodsCount)
      if (res.resultCode == 200) {
        this.getCartListAsync();
      }
    }
  },
  getters: {
    cartNum() {
      return this.cartList.reduce((prev, next) => {
        return prev + next.goodsCount;
      }, 0)
    }
  }
})